package com.revenant.driver.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.apkfuns.logutils.LogUtils;
import com.blankj.utilcode.util.AppUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.revenant.driver.App;
import com.revenant.driver.R;
import com.revenant.driver.bean.BaseBean.BaseTestBean;
import com.revenant.driver.bean.DriverTrackBean;

import static com.revenant.driver.utils.Constants.Driver_GetDriverCar_info;
import static com.revenant.driver.utils.Constants.Driver_Location_Upload;
import static com.revenant.driver.utils.Constants.Update_Zhong_Jiao;

/**
 * @ProjectName: Driver
 * @Package: com.revenant.driver.utils
 * @ClassName: LocationService
 * @Description: java类作用描述
 * @Author: Revenant
 * @CreateDate: 2020/4/13 12:44
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/4/13 12:44
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 * LocatinJiaoTongFileService
 */

public class LocationJiaoTongFileService extends Service {
    public static final String TAG = "LocationService";
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private static volatile AMapLocation lastLocation;

    @Nullable

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        initLocation();
        startLocation();

        if (Build.VERSION.SDK_INT >= 26) {
//            showNotify();
        }
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyLocation();
        Log.d(TAG, "onDestroy");
    }

    //显示通知栏
    public void showNotify() {
        startLocation();
        locationClient.enableBackgroundLocation(2001, buildNotification());
//        Notification.Builder builder = new Notification.Builder(getApplicationContext());
//        Intent nfIntent = new Intent(this, DriverMainActivity.class);
//        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0))
//                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher))
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentTitle("正在后台定位")
//                .setContentText("定位进行中")
//                .setWhen(System.currentTimeMillis());
//        Notification notification = builder.build();
//        notification.defaults = Notification.DEFAULT_SOUND;
//        //调用这个方法把服务设置成前台服务
//        startForeground(110, notification);

    }

    private void stopNotify() {
        PowerManager pm = (PowerManager) App.getApplication().getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();
        if (isScreenOn) {
            locationClient.disableBackgroundLocation(true);
        }
    }


    private void destroyLocation() {
        if (null != locationClient) {
            stopLocation();
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    private void initLocation() {
        locationClient = new AMapLocationClient(this);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    private void startLocation() {
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
        lastLocation = null;
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(1000 * 60 * 15 * 1);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Transport);
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    lastLocation = location;
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");
//                    SPUtils.setLongitude(App.getApplication(), String.valueOf(location.getLongitude()));
//                    SPUtils.setLatitude(App.getApplication(), String.valueOf(location.getLatitude()));
//                    initDataRecyclerview(String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()));
//                    String traceDesc = location.getAddress();
//                    uploadTrack(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), traceDesc, "2");
                    stopNotify();
                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");

                    //定位完成的时间
                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");

                    if (location.getErrorCode() == 12) {
                        showNotify();
                    }
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
//                tvResult.setText(result);
                LogUtils.d("定位数据是" + result);
            } else {
                LogUtils.d("定位失败，loc is null");
            }
        }
    };


    private String getGPSStatusString(int statusCode) {
        String str = "";
        switch (statusCode) {
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }

    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        LocationJiaoTongFileService getService() {
            return LocationJiaoTongFileService.this;
        }
    }

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    boolean isCreateChannel = false;

    @SuppressLint("NewApi")
    private Notification buildNotification() {

        Notification.Builder builder = null;
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(AppUtils.getAppName())
                .setContentText("正在运行")
                .setWhen(System.currentTimeMillis());

        if (Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }

    private void initDataRecyclerview(String lon, String lan) {
        OkGo.<String>post(Driver_GetDriverCar_info)
                .params("userId", SPUtils.getAccounId(App.getApplication()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DriverTrackBean listBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                        if (listBean.getCode().equals("0")) {
                            if (Integer.valueOf((Integer) listBean.getData())== 0) {
                                querensiconfirm(lon, lan);

                            }
                        }

                    }
                });
    }

    private void querensiconfirm(String lon, String lan) {
        OkGo.<String>post(Driver_Location_Upload)
                .params("x", lan)
                .params("y", lon)
                .params("userId", SPUtils.getAccounId(App.getApplication()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DriverTrackBean queRenSiBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                        if (queRenSiBean.getCode().equals("0")) {
                            LogUtils.d("位置上传");
                        }

                    }
                });
    }

    @Override
    public boolean stopService(Intent name) {
        Log.d(TAG, "stopService");
        return super.stopService(name);
    }


    /*上传司机轨迹（中交）*/

    private void uploadTrack(String lon, String lan, String traceDesc, String status) {
        OkGo.<String>post(Update_Zhong_Jiao)
                .params("x", lan)
                .params("y", lon)
                .params("userId", SPUtils.getAccounId(App.getApplication()))
                .params("traceDesc", traceDesc)
                .params("status", status)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        com.blankj.utilcode.util.LogUtils.d("test", response.body());
                        BaseTestBean testBean = GsonUtil.parseJsonWithGson(response.body(), BaseTestBean.class);
                        if (testBean.getCode().contains("0")) {


                        }
                    }
                });
    }

    public static AMapLocation getLastLocation() {
        return lastLocation;
    }
}
